#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "blog.h"
#include "blog_utils.h"
#include "../utils.h"
#include "../xmalloc.h"

__BLTIN_ST char *blog_var_args[] = { BLOG_LIMIT, BLOG_ACTION, NULL };
__BLTIN_VAR blog_var = { BLOG_VAR_NAME, blog_var_args, { __blog_preinit, NULL, __blog_init, __blog_free, NULL, __blog }, VAR_EXTENDED | VAR_TMPLT_REQ };

__BLTIN_RT void *db_handle;


#ifdef ENABLE_DEBUG
#define RNDS_LEN 10
static void
test_insert(void)
{
  char *rs = ncmalloc(RNDS_LEN+1, sizeof(char));
  gen_random_str(&rs, RNDS_LEN);
  blog_add_catg(db_handle, rs, rs);
  blog_new_blog_entry(db_handle, rs, rs, rs, rs, rs, 0);
  ncfree(rs, RNDS_LEN+1*sizeof(char));
}
#endif

int
__blog_preinit(void)
{
  url_register(BLOG_URI, BLOG_PATH, URL_BUILTIN, NULL);
  return (blog_create_tables());
}

int
__blog_init(void)
{
  int ret;

  ret = db_init(BLOG_DB_PRFIX, &db_handle);
  blog_utils_init(db_handle);
#ifdef ENABLE_DEBUG
  test_insert();
#endif
  return (ret);
}

int
__blog_free(void)
{
  blog_utils_free();
  db_close(db_handle);
  return (0);
}

void
__blog(const struct var_reqdata *vr)
{
  const tmpl_t *tmpl;
  tmpl_data_t *tmpl_data;
  string_t *tmp;
  const char *link;
  char *limit, *action;

  hashmap_get(vr->qry, BLOG_REQ_LINK, (any_t *) &link);
  TMPL_SIMPLE(tmpl, tmpl_data, vr, BLOG_TMPL_DEF);

  GET_ATTR(vr->attrs, BLOG_LIMIT, BLOG_LIMIT_DEF, limit);
  GET_ATTR(vr->attrs, BLOG_ACTION, BLOG_ACTION_SHOW, action);

  tmp = create_empty_string();

  if (strcmp(action, BLOG_ACTION_SHOW) == 0) {
    blog_show_posts(db_handle, &tmp, tmpl, tmpl_data, limit);
  } else if (strcmp(action, BLOG_ACTION_CONTENT) == 0 && link != NULL) {
    blog_show_post_content(db_handle, &tmp, tmpl, tmpl_data, link);
  }

  if (get_strlen(tmp) == 0) {
    set_string(tmp, "[Blog error]");
    E2("blog error");
  }
  add_sstring(vr->result, tmp);
  free_string(tmp);
}

